import 'package:flutter/material.dart';
import '../constants/app_theme.dart';

/// 天气选择器组件
/// 用于选择当前天气状况
class WeatherSelector extends StatefulWidget {
  /// 当前选中的天气
  final String? selectedWeather;
  
  /// 天气选择回调
  final Function(String?) onWeatherSelected;
  
  /// 是否只读模式
  final bool readOnly;
  
  /// 是否显示标题
  final bool showTitle;
  
  /// 布局方式
  final WeatherLayoutType layoutType;

  const WeatherSelector({
    super.key,
    this.selectedWeather,
    required this.onWeatherSelected,
    this.readOnly = false,
    this.showTitle = true,
    this.layoutType = WeatherLayoutType.grid,
  });

  @override
  State<WeatherSelector> createState() => _WeatherSelectorState();
}

class _WeatherSelectorState extends State<WeatherSelector>
    with TickerProviderStateMixin {
  late AnimationController _scaleController;
  late Animation<double> _scaleAnimation;
  
  // 天气选项
  static const List<WeatherOption> _weatherOptions = [
    WeatherOption(
      key: 'sunny',
      icon: Icons.wb_sunny,
      label: '晴天',
      color: Colors.orange,
    ),
    WeatherOption(
      key: 'cloudy',
      icon: Icons.wb_cloudy,
      label: '多云',
      color: Colors.grey,
    ),
    WeatherOption(
      key: 'rainy',
      icon: Icons.umbrella,
      label: '雨天',
      color: Colors.blue,
    ),
    WeatherOption(
      key: 'snowy',
      icon: Icons.ac_unit,
      label: '雪天',
      color: Colors.lightBlue,
    ),
    WeatherOption(
      key: 'windy',
      icon: Icons.air,
      label: '大风',
      color: Colors.teal,
    ),
    WeatherOption(
      key: 'foggy',
      icon: Icons.cloud,
      label: '雾霾',
      color: Colors.blueGrey,
    ),
    WeatherOption(
      key: 'stormy',
      icon: Icons.flash_on,
      label: '雷雨',
      color: Colors.purple,
    ),
    WeatherOption(
      key: 'hot',
      icon: Icons.whatshot,
      label: '炎热',
      color: Colors.red,
    ),
    WeatherOption(
      key: 'cold',
      icon: Icons.ac_unit_outlined,
      label: '寒冷',
      color: Colors.cyan,
    ),
  ];
  
  @override
  void initState() {
    super.initState();
    _initializeAnimations();
  }

  @override
  void dispose() {
    _scaleController.dispose();
    super.dispose();
  }

  /// 初始化动画
  void _initializeAnimations() {
    _scaleController = AnimationController(
      duration: const Duration(milliseconds: 150),
      vsync: this,
    );
    
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 0.95,
    ).animate(CurvedAnimation(
      parent: _scaleController,
      curve: Curves.easeInOut,
    ));
  }

  /// 处理天气选择
  void _handleWeatherSelection(String weatherKey) {
    if (widget.readOnly) return;
    
    // 播放缩放动画
    _scaleController.forward().then((_) {
      _scaleController.reverse();
    });
    
    // 如果点击的是已选中的天气，则取消选择
    final newWeather = widget.selectedWeather == weatherKey ? null : weatherKey;
    widget.onWeatherSelected(newWeather);
  }

  /// 获取天气选项
  WeatherOption? _getWeatherOption(String? weatherKey) {
    if (weatherKey == null) return null;
    return _weatherOptions.firstWhere(
      (option) => option.key == weatherKey,
      orElse: () => _weatherOptions.first,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标题
        if (widget.showTitle)
          _buildTitle(),
        
        // 天气选择器
        _buildWeatherSelector(),
      ],
    );
  }

  /// 构建标题
  Widget _buildTitle() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        children: [
          Icon(
            Icons.wb_sunny_outlined,
            size: 20,
            color: AppTheme.textSecondaryColor,
          ),
          const SizedBox(width: 8),
          Text(
            '天气状况',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w600,
              color: AppTheme.textPrimaryColor,
            ),
          ),
          if (widget.selectedWeather != null) ...[
            const SizedBox(width: 8),
            Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 8,
                vertical: 2,
              ),
              decoration: BoxDecoration(
                color: AppTheme.primaryColor.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(10),
              ),
              child: Text(
                _getWeatherOption(widget.selectedWeather)?.label ?? '',
                style: TextStyle(
                  fontSize: 12,
                  color: AppTheme.primaryColor,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建天气选择器
  Widget _buildWeatherSelector() {
    switch (widget.layoutType) {
      case WeatherLayoutType.horizontal:
        return _buildHorizontalLayout();
      case WeatherLayoutType.grid:
        return _buildGridLayout();
      case WeatherLayoutType.dropdown:
        return _buildDropdownLayout();
    }
  }

  /// 构建水平布局
  Widget _buildHorizontalLayout() {
    return SizedBox(
      height: 60,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: _weatherOptions.length,
        itemBuilder: (context, index) {
          final option = _weatherOptions[index];
          final isSelected = widget.selectedWeather == option.key;
          
          return Padding(
            padding: EdgeInsets.only(
              right: index < _weatherOptions.length - 1 ? 12 : 0,
            ),
            child: _buildWeatherItem(
              option: option,
              isSelected: isSelected,
              size: 50,
            ),
          );
        },
      ),
    );
  }

  /// 构建网格布局
  Widget _buildGridLayout() {
    return GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
        childAspectRatio: 1.2,
      ),
      itemCount: _weatherOptions.length,
      itemBuilder: (context, index) {
        final option = _weatherOptions[index];
        final isSelected = widget.selectedWeather == option.key;
        
        return _buildWeatherItem(
          option: option,
          isSelected: isSelected,
          showLabel: true,
        );
      },
    );
  }

  /// 构建下拉布局
  Widget _buildDropdownLayout() {
    return Container(
      padding: const EdgeInsets.symmetric(
        horizontal: 16,
        vertical: 12,
      ),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: AppTheme.dividerColor,
        ),
      ),
      child: DropdownButtonHideUnderline(
        child: DropdownButton<String>(
          value: widget.selectedWeather,
          hint: Row(
            children: [
              Icon(
                Icons.wb_sunny_outlined,
                color: AppTheme.textSecondaryColor,
                size: 20,
              ),
              const SizedBox(width: 8),
              Text(
                '选择天气',
                style: TextStyle(
                  color: AppTheme.textSecondaryColor,
                ),
              ),
            ],
          ),
          isExpanded: true,
          icon: Icon(
            Icons.keyboard_arrow_down,
            color: AppTheme.textSecondaryColor,
          ),
          items: [
            // 清除选择项
            DropdownMenuItem<String>(
              value: null,
              child: Row(
                children: [
                  Icon(
                    Icons.clear,
                    color: AppTheme.textSecondaryColor,
                    size: 20,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    '清除选择',
                    style: TextStyle(
                      color: AppTheme.textSecondaryColor,
                    ),
                  ),
                ],
              ),
            ),
            // 天气选项
            ..._weatherOptions.map((option) {
              return DropdownMenuItem<String>(
                value: option.key,
                child: Row(
                  children: [
                    Icon(
                      option.icon,
                      color: option.color,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Text(option.label),
                  ],
                ),
              );
            }),
          ],
          onChanged: widget.readOnly ? null : (value) {
            widget.onWeatherSelected(value);
          },
          selectedItemBuilder: (context) {
            return [
              // 清除选择项的显示
              Row(
                children: [
                  Icon(
                    Icons.clear,
                    color: AppTheme.textSecondaryColor,
                    size: 20,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    '清除选择',
                    style: TextStyle(
                      color: AppTheme.textSecondaryColor,
                    ),
                  ),
                ],
              ),
              // 天气选项的显示
              ..._weatherOptions.map((option) {
                return Row(
                  children: [
                    Icon(
                      option.icon,
                      color: option.color,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      option.label,
                      style: TextStyle(
                        color: AppTheme.textPrimaryColor,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                );
              }),
            ];
          },
        ),
      ),
    );
  }

  /// 构建天气项
  Widget _buildWeatherItem({
    required WeatherOption option,
    required bool isSelected,
    double size = 60,
    bool showLabel = false,
  }) {
    return AnimatedBuilder(
      animation: _scaleAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: isSelected ? _scaleAnimation.value : 1.0,
          child: GestureDetector(
            onTap: () => _handleWeatherSelection(option.key),
            child: Container(
              width: showLabel ? null : size,
              height: showLabel ? null : size,
              padding: EdgeInsets.all(showLabel ? 12 : 8),
              decoration: BoxDecoration(
                color: isSelected
                    ? option.color.withValues(alpha: 0.1)
                    : AppTheme.surfaceColor,
                borderRadius: BorderRadius.circular(12),
                border: Border.all(
                  color: isSelected ? option.color : AppTheme.dividerColor,
                  width: isSelected ? 2 : 1,
                ),
                boxShadow: isSelected
                    ? [
                        BoxShadow(
                          color: option.color.withValues(alpha: 0.2),
                          blurRadius: 8,
                          spreadRadius: 2,
                        ),
                      ]
                    : null,
              ),
              child: showLabel
                  ? Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          option.icon,
                          color: isSelected ? option.color : AppTheme.textSecondaryColor,
                          size: 24,
                        ),
                        const SizedBox(height: 4),
                        Text(
                          option.label,
                          style: TextStyle(
                            fontSize: 12,
                            color: isSelected
                                ? option.color
                                : AppTheme.textSecondaryColor,
                            fontWeight: isSelected
                                ? FontWeight.w600
                                : FontWeight.normal,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ],
                    )
                  : Icon(
                      option.icon,
                      color: isSelected ? option.color : AppTheme.textSecondaryColor,
                      size: size * 0.4,
                    ),
            ),
          ),
        );
      },
    );
  }
}

/// 天气布局类型
enum WeatherLayoutType {
  horizontal, // 水平滚动
  grid,       // 网格布局
  dropdown,   // 下拉选择
}

/// 天气选项
class WeatherOption {
  /// 天气键值
  final String key;
  
  /// 图标
  final IconData icon;
  
  /// 标签
  final String label;
  
  /// 颜色
  final Color color;

  const WeatherOption({
    required this.key,
    required this.icon,
    required this.label,
    required this.color,
  });
}

/// 紧凑天气显示
/// 用于在列表中显示天气信息
class CompactWeatherDisplay extends StatelessWidget {
  /// 天气键值
  final String? weather;
  
  /// 大小
  final double size;
  
  /// 是否显示标签
  final bool showLabel;

  const CompactWeatherDisplay({
    super.key,
    this.weather,
    this.size = 20,
    this.showLabel = false,
  });

  /// 获取天气选项
  WeatherOption? _getWeatherOption() {
    if (weather == null) return null;
    
    const options = [
      WeatherOption(
        key: 'sunny',
        icon: Icons.wb_sunny,
        label: '晴天',
        color: Colors.orange,
      ),
      WeatherOption(
        key: 'cloudy',
        icon: Icons.wb_cloudy,
        label: '多云',
        color: Colors.grey,
      ),
      WeatherOption(
        key: 'rainy',
        icon: Icons.umbrella,
        label: '雨天',
        color: Colors.blue,
      ),
      WeatherOption(
        key: 'snowy',
        icon: Icons.ac_unit,
        label: '雪天',
        color: Colors.lightBlue,
      ),
      WeatherOption(
        key: 'windy',
        icon: Icons.air,
        label: '大风',
        color: Colors.teal,
      ),
      WeatherOption(
        key: 'foggy',
        icon: Icons.cloud,
        label: '雾霾',
        color: Colors.blueGrey,
      ),
      WeatherOption(
        key: 'stormy',
        icon: Icons.flash_on,
        label: '雷雨',
        color: Colors.purple,
      ),
      WeatherOption(
        key: 'hot',
        icon: Icons.whatshot,
        label: '炎热',
        color: Colors.red,
      ),
      WeatherOption(
        key: 'cold',
        icon: Icons.ac_unit_outlined,
        label: '寒冷',
        color: Colors.cyan,
      ),
    ];
    
    try {
      return options.firstWhere((option) => option.key == weather);
    } catch (e) {
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    final option = _getWeatherOption();
    
    if (option == null) {
      return const SizedBox.shrink();
    }
    
    if (showLabel) {
      return Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            option.icon,
            color: option.color,
            size: size,
          ),
          SizedBox(width: size * 0.3),
          Text(
            option.label,
            style: TextStyle(
              fontSize: size * 0.7,
              color: option.color,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      );
    }
    
    return Icon(
      option.icon,
      color: option.color,
      size: size,
    );
  }
}